function CountdownTimer(option) {
  let defaultOption = {
    milliseconds: 10000, // 倒计时毫秒数
    interval: 1000, // 倒计时间隔毫秒数
    oninit(obj) { // 倒计时初始化回调
      console.log(obj);
    },
    onreset(obj) { // 倒计时重置回调
      console.log(obj);
    },
    oneach(obj) { // 倒计时每次间隔回调
      console.log(obj);
    },
    onstart(obj) { // 倒计时开始回调
      console.log(obj);
    },
    onend(obj) { // 倒计时结束回调
      console.log(obj);
    },
  }
  Object.assign(this, defaultOption, option);
  this.remaining = this.milliseconds; // 倒计时剩余毫秒数
  this.oninit(this.fmtRemain(this.remaining));
}

Object.assign(CountdownTimer.prototype, {
  DMS: 1000 * 3600 * 24, // 一天有多少毫秒
  HMS: 1000 * 3600, // 一小时有多少毫秒
  MMS: 1000 * 60, // 一分钟有多少毫秒
  SMS: 1000, // 一秒有多少毫秒
  DS: 3600 * 24, // 一天有多少秒
  HS: 3600, // 一小时有多少秒
  MS: 60, // 一分钟有多少秒
  raf: null, // requestAnimationFrame的id
  dhms(remain) { // 将剩余毫秒数转为天时分秒对象
    let s = Math.round(remain / 1000);
    let d = Math.floor(s / this.DS);
    s -= d * this.DS;
    let h = Math.floor(s / this.HS);
    s -= h * this.HS;
    let m = Math.floor(s / this.MS);
    s -= m * this.MS;
    return { d, h, m, s }; // 剩余d天h时m分s秒
  },
  dhmsms(remain) { // 将剩余毫秒数转为天时分秒毫秒对象
    let ms = remain;
    let d = Math.floor(ms / this.DMS);
    ms -= d * this.DMS;
    let h = Math.floor(ms / this.HMS);
    ms -= h * this.HMS;
    let m = Math.floor(ms / this.MMS);
    ms -= m * this.MMS;
    let s = Math.floor(ms / this.SMS);
    ms -= s * this.SMS;
    return { d, h, m, s, ms }; // 剩余d天h时m分s秒ms毫秒
  },
  fmtRemain(remain) { // 将剩余毫秒数转为友好的数据
    return {
      remain,
      dhms: this.dhms(remain),
      dhmsms: this.dhmsms(remain),
    };
  },
  start() { // 开始倒计时
    this.onstart(this.fmtRemain(this.remaining));
    let now = Date.now();
    this.deadline = now + this.remaining; // 倒计时结束时的时间戳，通过它来计算剩余时间最靠谱
    let loop = () => {
      this.raf = requestAnimationFrame(loop); // 下一帧
      let now = Date.now();
      let remain = this.deadline - now; // 计算当前剩余毫秒数
      if (remain > 0) { // 剩余毫秒数大于0
        if (this.remaining - remain >= this.interval) { // 判断是否满足倒计时间隔
          this.remaining = remain;
          let dhms = this.fmtRemain(remain);
          this.oneach(dhms); // 执行每次间隔回调
        }
      } else { // 剩余毫秒数小于0，表示倒计时结束
        this.stop();
        let dhms = this.fmtRemain(0);
        this.onend(dhms);
      }
    };
    loop();
  },
  stop() { // 暂停倒计时
    cancelAnimationFrame(this.raf);
  },
  reset() { // 重置倒计时
    this.stop();
    this.remaining = this.milliseconds;
    this.onreset(this.fmtRemain(this.remaining));
  },
  setMilliseconds(ms) { // 设置倒计时毫秒数
    this.stop();
    this.remaining = this.milliseconds = ms; // 倒计时剩余毫秒数
    this.oninit(this.fmtRemain(this.remaining));
  },
});

// export default CountdownTimer;
